package com.prs.crm.action.oa;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.action.FlowAction;
import com.prs.crm.annotation.Clew;
import com.prs.crm.annotation.FlowActive;
import com.prs.crm.annotation.FlowStart;
import com.prs.crm.context.AppContext;
import com.prs.crm.context.Constrains;
import com.prs.crm.context.FileUtil;
import com.prs.crm.context.ToolKits;
import com.prs.crm.domain.doc.DocLevel;
import com.prs.crm.domain.doc.DocType;
import com.prs.crm.domain.doc.Document;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.domain.oa.Apply;
import com.prs.crm.domain.oa.ApplyAudit;
import com.prs.crm.domain.oa.ApplyCritique;
import com.prs.crm.domain.oa.OaTaskKeyWord;
import com.prs.crm.report.ReportUtils;
import com.prs.crm.service.doc.DocumentService;
import com.prs.crm.service.flow.WorkFlowInstanceService;
import com.prs.crm.service.flow.WorkFlowProcessService;
import com.prs.crm.service.oa.ApplyAuditService;
import com.prs.crm.service.oa.ApplyCritiqueService;
import com.prs.crm.service.oa.ApplyService;
import com.prs.crm.service.oa.OaTaskKeyWordService;

public class ApplyAction extends FlowAction<Apply> {

	private static final long serialVersionUID = 1L;
	private static final String key = "com.prs.crm.oa.applyDockey";
	private Apply apply;
	private ApplyService applyService;

	private OaTaskKeyWord oaTaskKeyWord;
	private OaTaskKeyWordService oaTaskKeyWordService;

	private Document document;
	private DocumentService documentService;

	private ApplyAudit applyAudit;
	private ApplyAuditService applyAuditService;

	private ApplyCritique applyCritique;
	private ApplyCritiqueService applyCritiqueService;

	private PaginationSupport pagination;
	private Integer[] ids;

	private File upload;
	private String uploadFileName;

	private Person lowerAuditPerson;
	private String copyToPersons;
	private String appIds;
	private Collection<Document> relatDocs;

	private String[] names;
	private String[] codes;
	private DocType[] types;
	private String[] files;
	private DocLevel[] levels;
	private String[] keyWords;
	private String[] keyNames;
	private String flow;
	@Action("listApply")
	public String execute() {
		return SUCCESS;
	}

	@Action("listApplyByLevel")
	public String listApplyByLevel() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Apply.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		if (appIds != null) {
			if (!"all".equals(appIds)) {
				Collection<Integer> personIds = new ArrayList<Integer>();
				String levels = "";
				for (String val : appIds.split(",")) {
					if (val.indexOf("dept") == -1) {
						if (ToolKits.isInteger(val)) {
							personIds.add(Integer.parseInt(val));
						} else {
							levels = val;
						}
					}
				}
				if (personIds.size() > 0) {
					criteria.createAlias("recorder", "ri");
					criteria.add(Restrictions.in("ri.id", personIds));
				}
				if (!"".equals(levels.trim())) {
					criteria.add(Restrictions.eq("level", ReportUtils
							.URLDecode(levels.trim())));
				}
			}
		}
		this.setPagination(this.getApplyService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@FlowActive(target = "apply", flowservice = "applyService")
	@Action("editApply")
	public String edit() {
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@FlowStart(target = "apply", flowservice = "applyService")
	@Action(value = "saveApply", results = { @Result(name = "success", type = "redirect", location = "editApply") ,
			 @Result(name = "error", type = "chain", location = "editApply")})
	public String save() {
		if (apply.getTitle() == null || "".equals(apply.getTitle().trim())) {
			addActionError("主题不能为空");
			return ERROR;
		}
		if (copyToPersons == null || "".equals(copyToPersons)) {
			addActionError("抄送不能为空");
			return ERROR;
		}
		if (apply.getLevel() == null) {
			addActionError("级别不能为空");
			return ERROR;
		}
		if (names == null) {
			addActionError("任务档案不能为空");
			return ERROR;
		}
		if(flow==null||"".equals(flow.trim())){
			addActionError("请添加审核流程");
			return ERROR;
		}
	
		this.getApplyService().saveApply(apply, upload, uploadFileName,
				copyToPersons);
		relatDocs = this.getStorDocs();
		relatDocs = new ArrayList<Document>();
		for (int i = 0; i < names.length; i++) {
			Document od = new Document();
			od.setName(names[i]);
			od.setDocumentcode(codes[i]);
			od.setLevel(levels[i]);
			od.setType(types[i]);
			String keyN = keyNames[i].replaceAll(",", " ");
			od.setKeyWord(keyN);
			File StringToFile = new File(files[i]);
			od.setAttach(FileUtil.getInstance().createAttach(StringToFile,
					StringToFile.getName()));

			relatDocs.add(od);
		}
		List<Document> rlist = (List<Document>) relatDocs;
		for (int o = 0; o < rlist.size(); o++) {
			Document doc = rlist.get(o);
			String keyW[] = keyWords[o].split(",");
			for (int k = 0; k < keyW.length; k++) {
//				if(keyW[k]==null||"".equals(keyW[k].trim())){
//					addActionError("关键字不能为空");
//					return ERROR;
//				}
				OaTaskKeyWord Ootkw = this.getOaTaskKeyWordService()
						.getOaTaskKeyWord(Integer.parseInt(keyW[k]));
				doc.getOaTaskKeyWord().add(Ootkw);
			}
			doc.setId(null);
			doc.setApply(apply);
			this.getDocumentService().submitDocument(doc);

		}
		
		this.setPrompt("公务提交成功!");
		return SUCCESS;
	}

	@Action("viewApply")
	public String viewApply() {
		Iterator<Person> iter = apply.getCopyToPersons().iterator();
		copyToPersons = "";
		while (iter.hasNext()) {
			copyToPersons += iter.next().getResume().getName() + " , ";
		}
		this.displayEndNodes(apply);
		return SUCCESS;
	}

	@Action("listCritiqueApply")
	public String listCritiqueApply() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Apply.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		Person person = AppContext.getAccountContext().currentUser();
		criteria.add(Restrictions.eq("flowstatus",
				Constrains.WORKFLOWENTITY_STATE_PROCESS));
		criteria.createAlias("copyToPersons", "c").add(
				Restrictions.eq("c.id", person.getId()));
		this.setPagination(this.getApplyService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("viewCritiqueApply")
	public String viewCritiqueApply() {
		return SUCCESS;
	}

	@Action("editCritiqueApply")
	public String editCritiqueApply() {
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "submitCritiqueApply", results = { @Result(name = "success", type = "redirect", location = "listCritiqueApply") })
	public String submitCritiqueApply() {
		this.setPrompt("提交点评成功");
		applyCritique.setApply(apply);
		this.getApplyCritiqueService().saveApplyCritique(applyCritique, upload,
				uploadFileName);
		return SUCCESS;
	}

	@Action("listMyPassApply")
	public String listMyPassApply() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Apply.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		Person person = AppContext.getAccountContext().getUser();
		criteria.add(Property.forName("recorder").eq(person));
		criteria.add(Property.forName("flowstatus").eq(
				Constrains.WORKFLOWENTITY_STATE_VALID));
		this.setPagination(this.getApplyAuditService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("listMyNotPassApply")
	public String listMyNotPassApply() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Apply.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		Person person = AppContext.getAccountContext().getUser();
		criteria.add(Property.forName("recorder").eq(person));
		criteria.add(Property.forName("flowstatus").eq(
				Constrains.WORKFLOWENTITY_STATE_INVALID));
		this.setPagination(this.getApplyAuditService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action(value = "removeApply", results = { @Result(name = "success", type = "redirect", location = "listApply") })
	public String remove() {
		this.getApplyService().batchRemove(ids);
		return SUCCESS;
	}

	public Apply getApply() {
		return apply;
	}

	public void setApply(Apply apply) {
		this.apply = apply;
	}

	public ApplyService getApplyService() {
		return applyService;
	}

	public void setApplyService(ApplyService applyService) {
		this.applyService = applyService;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public ApplyCritique getApplyCritique() {
		return applyCritique;
	}

	public void setApplyCritique(ApplyCritique applyCritique) {
		this.applyCritique = applyCritique;
	}

	public ApplyCritiqueService getApplyCritiqueService() {
		return applyCritiqueService;
	}

	public void setApplyCritiqueService(
			ApplyCritiqueService applyCritiqueService) {
		this.applyCritiqueService = applyCritiqueService;
	}

	public Integer[] getIds() {
		return ids;
	}

	public void setIds(Integer[] ids) {
		this.ids = ids;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public ApplyAudit getApplyAudit() {
		return applyAudit;
	}

	public void setApplyAudit(ApplyAudit applyAudit) {
		this.applyAudit = applyAudit;
	}

	public ApplyAuditService getApplyAuditService() {
		return applyAuditService;
	}

	public void setApplyAuditService(ApplyAuditService applyAuditService) {
		this.applyAuditService = applyAuditService;
	}

	public void setLowerAuditPerson(Person lowerAuditPerson) {
		this.lowerAuditPerson = lowerAuditPerson;
	}

	public Person getLowerAuditPerson() {
		return lowerAuditPerson;
	}

	public void setCopyToPersons(String copyToPersons) {
		this.copyToPersons = copyToPersons;
	}

	public String getCopyToPersons() {
		return copyToPersons;
	}

	public String getAppIds() {
		return appIds;
	}

	public void setAppIds(String appIds) {
		this.appIds = appIds;
	}

	public Document getDocument() {
		return document;
	}

	public void setDocument(Document document) {
		this.document = document;
	}

	public DocumentService getDocumentService() {
		return documentService;
	}

	public void setDocumentService(DocumentService documentService) {
		this.documentService = documentService;
	}

	public String[] getNames() {
		return names;
	}

	public void setNames(String[] names) {
		this.names = names;
	}

	public String[] getCodes() {
		return codes;
	}

	public void setCodes(String[] codes) {
		this.codes = codes;
	}

	public DocType[] getTypes() {
		return types;
	}

	public void setTypes(DocType[] types) {
		this.types = types;
	}

	public String[] getFiles() {
		return files;
	}

	public void setFiles(String[] files) {
		this.files = files;
	}

	public DocLevel[] getLevels() {
		return levels;
	}

	public void setLevels(DocLevel[] levels) {
		this.levels = levels;
	}

	public String[] getKeyWords() {
		return keyWords;
	}

	public void setKeyWords(String[] keyWords) {
		this.keyWords = keyWords;
	}

	public String[] getKeyNames() {
		return keyNames;
	}

	public void setKeyNames(String[] keyNames) {
		this.keyNames = keyNames;
	}

	public Collection<Document> getRelatDocs() {
		return relatDocs;
	}

	public void setRelatDocs(Collection<Document> relatDocs) {
		this.relatDocs = relatDocs;
	}

	public OaTaskKeyWord getOaTaskKeyWord() {
		return oaTaskKeyWord;
	}

	public void setOaTaskKeyWord(OaTaskKeyWord oaTaskKeyWord) {
		this.oaTaskKeyWord = oaTaskKeyWord;
	}

	public OaTaskKeyWordService getOaTaskKeyWordService() {
		return oaTaskKeyWordService;
	}

	public void setOaTaskKeyWordService(
			OaTaskKeyWordService oaTaskKeyWordService) {
		this.oaTaskKeyWordService = oaTaskKeyWordService;
	}

	@SuppressWarnings("unchecked")
	public Collection<Document> getStorDocs() {
		return (Collection<Document>) this.getStorage().get(key);
	}

	public String getFlow() {
		return flow;
	}

	public void setFlow(String flow) {
		this.flow = flow;
	}
}
